package com.zbkj.service.service.standard.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.common.model.standard.PeStandardResult;

import com.zbkj.common.response.standard.ReportDetailResponse;
import com.zbkj.service.dao.standard.PeStandardResultMapper;
import com.zbkj.service.service.standard.IPeStandardResultService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2025-08-11
 */
@Service
public class PeStandardResultServiceImpl extends ServiceImpl<PeStandardResultMapper, PeStandardResult> implements IPeStandardResultService {

    @Override
    public List<ReportDetailResponse> reportDetail(Long standardId) {
        List<PeStandardResult> list = this.lambdaQuery().eq(PeStandardResult::getStandardId, standardId)
                .orderByAsc(PeStandardResult::getSort).list();
        List<ReportDetailResponse> dbList = new ArrayList<>();
        for (PeStandardResult peStandardResult : list) {
            ReportDetailResponse reportDetailResponse = new ReportDetailResponse();
            BeanUtils.copyProperties(peStandardResult, reportDetailResponse);
            dbList.add(reportDetailResponse);
        }

        Map<Long, List<ReportDetailResponse>> childMap = new HashMap<>();
        dbList.forEach(item -> {
            if(childMap.containsKey(item.getParentId())){
                childMap.get(item.getParentId()).add(item);
            }else{
                ArrayList<ReportDetailResponse> peStandards = new ArrayList<>();
                peStandards.add(item);
                childMap.put(item.getParentId(), peStandards);
            }
        });
        List<ReportDetailResponse> levelOne = dbList.stream().filter(item -> item.getLevel() == 1).collect(Collectors.toList());
        for (ReportDetailResponse peStandard : levelOne) {
            List<ReportDetailResponse> peStandards = childMap.get(peStandard.getId());
            if(ObjectUtils.isNotEmpty(peStandards)){
                peStandard.setChilds(peStandards);
            }
        }
        return levelOne;
    }

}
